package com.boot.util;

import com.boot.model.WordGenConfig;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.ParserContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SpelUtils {

    public static String getValue(String template, Map<String, Object> data) {
        return getValue(template, Arrays.asList(data));
    }


    public static String getValue(String template, WordGenConfig wordGenConfig) {
        return getValue(template, Arrays.asList(new HashMap<String,Object>(){{
             put("audTrm", wordGenConfig.getAudTrm());
             put("prvdId", wordGenConfig.getPrvdId());
        }}));
    }

    //    splange 拼接
    public static String getValue(String template, List<Map<String, Object>> list) {
        StringBuilder sb = new StringBuilder();
        ExpressionParser parser = new SpelExpressionParser();
        ParserContext parserContext = new ParserContext() {
            @Override
            public boolean isTemplate() {
                return true;
            }

            @Override
            public String getExpressionPrefix() {
                return "{";
            }

            @Override
            public String getExpressionSuffix() {
                return "}";
            }
        };
        Expression expression = parser.parseExpression(template, parserContext);
        for (Map<String, Object> map : list) {
            StandardEvaluationContext ctx = new StandardEvaluationContext();
            ctx.setVariables(map);
            sb.append(expression.getValue(ctx, String.class));
        }
        return sb.toString();
    }
}
